<?php
namespace Admin\Controller;
use Think\Controller;

class GoodsController extends CommonController {

    private $user_id;

    public function _initialize(){
        parent::_initialize();
        // $access=\Home\Common\checkpower(10);
        // if($access!==0){
        //     $this->error('权限不够');
        // }
    }

    public function __construct()
    {
        parent::__construct();
        $this->user_id = is_login();
    }
    
    public function index(){

    	$goods = M('goods');
        $title = I('title');
        $price1 = I('price1', 0);
        $price2 = I('price2', 0);

        $where = array('status' => 1);
        if(!empty($title)){   //构造搜索条件
            $where['title'] = array('like','%'.$title.'%');
        }

        if((!empty($price1)) && (!empty($price2))){
            $where['cost_price'] = array('between',array($price1, $price2));
        }else if(!empty($price1)){
            $where['cost_price'] = array('gt',$price1);
        }else if(!empty($price2)){
            $where['cost_price'] = array('lt',$price2);
        }


        $count = $goods
                    ->where($where)
                    ->count(); //查询满足条件的总记录数
        
        $page = new \Think\Page($count,10);
        $show = $page->show(); //分页显示输出
        $data = $goods
            ->limit($page->firstRow.','.$page->listRows)
            ->where($where)
            ->select();
        
        $this->assign('page',$show);
    	$this->assign('data', $data);
       	$this->display();
    }


    //商品详情表
    function detail(){

        $goods = M('goods');
        $gid   = I('get.gid');
        if (!$gid) return $this->error('请传递正确的商品ID', U('Goods/index'));
        $goodsData = $goods->find($gid);
        if (!$goodsData) return $this->error('商品信息未找到', U('Goods/index'));

        $this->assign('goodData',$goodsData);
        $this->display();
    }


    //添加商品
    public function add(){

    	$cate_model   = M('category');
        $source_model = M('platform');

    	$r = $cate_model->order('cate_path')
                        ->where('status=1')
                        ->select();
    	$r = $this->nav_tree($r, 0);
    	$options = $this->option($r);

        $source_option = $source_model->where(array('status'=>1))
                                      ->getField('id, name');

        $drawer_list = $this->get_user_drawer();

        $this->assign('source_option',$source_option);
        $this->assign('drawer_list',$drawer_list);
    	$this->assign('options',$options);
    	$this->display();
    }

    /**
     * 获得用户的分类id和title
     * @return mixed
     */
    private function get_user_drawer()
    {
        $filter = array('uid' => $this->user_id, 'status' => 1);
        return M('drawer')->where($filter)->getField('id, title');
    }

    //商品添加处理函数
    function add_doit(){

		//获取整个表单数据并赋值给$data
		$data = I('post.');
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['post_uid'] = $this->user_id;

        //上传图片
        $pic = $this->upload();
        if($pic){
            $data['cover'] = $pic['cover'];
        }
		
		//需要同时把数据添加到几张表中去，tp中有简便的处理方法
		$goods            = M('goods');
		$goods_img_model  = M('goods_image');

		if($goods->create($data)){
			//添加数据到goods中获得插入的id作为下次添加的源数据使用
			$res = $goods->add();

			if($res){
                if($pic['cover'] && $pic['thumb']) {
                    $info = array('goods_id' => $res, 'cover' => $pic['cover'], 'thumb'=>$pic['thumb']);
                    $goods_img_model->add($info);
                }
                $this->success('数据添加成功',U('Goods/index'));
			}else{
				$this->error($goods->getError(), U('Goods/index'));
			}
		}

    }


    //编辑商品信息
    public function edit(){
    	$goods       = M('goods');
    	$cate_model  = M('category'); //用来获取相应的分类信息
    	$gid         = I('gid');

        $goods_info = $goods->find($gid);
        if (!$goods_info) $this->error('请传递正确的商品id', U('Goods/index'));

    	//获取商品的分类信息,根据 cate_path 排序
    	$cate     = $cate_model->order('cate_path')->select(); //二维数组
    	$cateData = $this->nav_tree($cate);
    	$cateOptions = $this->option($cateData,$goods_info['category_id']);

        $drawer_list = $this->get_user_drawer();

        $source_option = M('platform')->where(array('status'=>1))
                                      ->getField('id, name');

    	//将产品id分配过去放入隐藏表单中
    	$this->assign('gid',$gid);
    	$this->assign('data',$goods_info);
    	//将图片的地址分配到隐藏表单中..
    	$this->assign('cateOptions',$cateOptions);
    	$this->assign('source_option',$source_option);
    	$this->assign('drawer_list',$drawer_list);
    	$this->display();
    }


    function edit_doit(){
    	$data = I('post.');
    	$gid  = I('id', 0);    //隐藏域传递过来的商品id
    	$data['ori_price']  = I('ori_price', 0);
    	$data['cost_price'] = I('cost_price', 0);
        $img_ori = I('post.cover');
        $goods_model = M('goods');

        if (!$gid) return $this->error('请传递正确的商品ID', U('Goods/index'));
        $goods_info = $goods_model->find($gid);
        if (!$goods_info) return $this->error('未找到正确的商品信息', U('Goods/index'));

    	//这三个需要根据条件来判断，如果有重新上传图片，那么就删除旧的图片并重新生成新的图片并写入数据库，如果没有，则不更新proImg表
    	//判断图片是否上传以及如何处理
    	if($_FILES['img']['error'] === 0){ //如果图片上传
    		$pic = $this->upload();
    		$data['cover'] = $pic['cover'];
    	}

    	//需要同时把数据添加到几张表中去，tp中有简便的处理方法
        if($goods_model->create($data)) {
            $res = $goods_model->where("id=".$gid)->save();
            if($res != false){
                $this->success('数据更新成功',U('Goods/index'));
            } else {
                $this->error('数据更新失败',U('Goods/index'));
            }
        }
    }


    public function delete(){
        $goods = M('goods');
        $gid   = I('get.gid');
        if (!$gid) return $this->error('请传递正确的商品ID', U('Goods/index'));
        $goods_info = $goods->find($gid);
        if (!$goods_info) return $this->error('商品信息未找到', U('Goods/index'));

        $info = array('status' => 0);
        $res   = $goods->where(array('id' => $gid))->save($info);
        if($res){
            $this->success('删除成功',U('Goods/index'));
        }else{
            $this->error('删除失败',U('Goods/index'));
        }
    }


    protected function upload($url){ //上传图片，如果有传递$url参数的话就删除对应的图片
    	$upload = new \Think\Upload(); //实例化tp的上传类
    	$upload->exts = array('jpg','gif','png','jpeg'); //设置附件上传类型
    	$upload->rootPath = './Public/Uploads/'; //相对于站点根目录jd
    	$upload->savePath = ''; //设置附件上传目录,地址是相对于根目录(rootPath的)

    	$info = $upload->upload(); //开始上传
    	if(!$info){
    		$this->error($upload->getError());
    	}else{
    		foreach($info as $v) {
    			$pic['file'] = $v['savepath'].$v['savename']; //获取文件名
                //ori是根据需要进行更改的
                $pic['cover'] = $v['savepath'].'400_'.$v['savename'];
    			$pic['thumb'] = $v['savepath'].'50_'.$v['savename']; //获取缩略图的文件名
    			$pic['img'] = $upload->rootPath.$v['savepath'].$v['savename']; //获取完整的图片地址

    			$image = new \Think\Image(); // 利用tp的图片处理类对上传的图片进行处理
    			$image->open($pic['img']);
    			
                $image->thumb(400, 400)->save($upload->rootPath.$v['savepath'].'400_'.$v[savename]);
    			$image->thumb(50, 50)->save($upload->rootPath.$v['savepath'].'50_'.$v[savename]);

    			return $pic; //返回相关信息数组
    	}
    }
  }


    //递归获取分类信息
    protected function nav_tree($data, $pid=0){
   	$arr = array();
   	foreach($data as $v){
   		if($v['pid'] == $pid){
   			$v['child'] = $this->nav_tree($data, $v['id']);
   			$arr[] = $v;
   		}
   	}
   	return $arr;
   }

   	//根据传入的数组生成对应的option
    private function option($r, $id){
    	//如果有传cateid，则当前的分类为选中状态
	   	$cateid = $id ? $id : 0;
	   	$disabled = '';	//判断分类是否需要禁用(如果当前分类下面还有子分类，那么在商品的时候，该分类就应该隐藏，因为非最终目录下面是不能够有商品的)
	   	$selected = ''; // 判断分类是否选中，如果被选中，其值为select，没有选中的话其值为空
	   	$options = '';  //用来存储我们要生成的option信息

	   	//通过遍历获得我们需要的格式组成的option
	   	foreach($r as $v){ //第一层的遍历
	   		if($v['id'] == $id){
	   			$selected = 'selected';
	   		}
	   		$options .= '<option value="'.$v['id'].'" '.$selected.' disabled>'.$v['cate_name'].'</option>';
	   		$selected = ''; //及时的将$selected的值清空，保证后面的状态

	   			if($v['child']){
	   				foreach ($v['child'] as $v2) { //第二层分类
	   					if($v2['id'] == $id){
	   						$selected = "selected";
	   					}
                        if($v2['child']){
                        //如果仍然有子级的话，就加上disabled
                            $options.= '<option value="'.$v2['id'].'" '.$selected.' disabled>&nbsp;&nbsp;&nbsp;&nbsp;'.$v2['cate_name'].'</option>';
                        $selected = '';

                        }else{ //如果没有子级的话
	   					$options.= '<option value="'.$v2['id'].'" '.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;'.$v2['cate_name'].'</option>';
	   					$selected = '';
                        }
                            if($v2['child']){ //第三层分类
                                foreach ($v2['child'] as $v3) {
                                    if($v3['id'] == $id){
                                        $selected = "selected";
                                    }

                                    $options.= '<option value="'.$v3['id'].'" '.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$v3['cate_name'].'</option>';
                                    $selected = '';
                            }
                        }
	   			}
	   		}
	   	}
	   	return $options;
   }
   

    private function order($data, $parentid=0) {
		static $arr = array();
		foreach($data as $volist) {
			if($volist['parentid'] == $parentid) { // 得到所有的一级分类
				$arr[] = $volist;
				// 继续调用当前方法  - 递归函数
				$this->order($data, $volist['id']);
			}
		}
		return $arr;
	}


	function nav_tree2() {
		$kinds = M('lamp86_shop.kinds','tb_');
		// 将表中所有的数据都查到
		$data = $kinds -> select();
		// 获取所有的一级分类
		$r=$this->order2($data);
		
		foreach($r as $v) {
			echo $v['name'].'<br>';
			foreach($v['child'] as $v1) {
				echo '&nbsp;&nbsp;&nbsp;&nbsp;'.$v1['name'].'<br>';
				foreach($v1['child'] as $v2) {
					echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$v2['name'].'<br>';
			
				}
			}
		}
		
	}


	private function order2($data, $parentid=0) {
		$arr = array();
		foreach($data as $volist) {
			if($volist['parentid'] == $parentid) { // 得到所有的一级分类
				$volist['child'] = $this->order2($data, $volist['id']);
				$arr[] = $volist;
				// 继续调用当前方法  - 递归函数
			}
		}
		return $arr;
	}



}
